package com.yupi.yuapiinterface.aop;

import com.yupi.yuapiinterface.annotation.ApiCount;
import com.yupi.yuapiinterface.model.User;
import com.yupi.yuapiinterface.model.UserInterfaceLog;
import com.yupi.yuapiinterface.service.UserInterfaceLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 调用次数统计切面
 *
 */
@Aspect
@Component
@Slf4j
@Order(2)
public class InvokeCountAspect {

    @Resource
    private UserInterfaceLogService userInterfaceLogService;

    @Around("@annotation(apiCount)")
    public Object doInvokeCount(ProceedingJoinPoint joinPoint, ApiCount apiCount) throws Throwable {
        try {
            // 调用目标方法
            Object result = joinPoint.proceed();
            //上下文拿到用户信息
            User user =(User) getRequest().getAttribute("user");
            //分布式session拿到用户信息.但是不会待cookie里面的sessionID来进来，需要手动设置请求头
             //获得当前请求
//            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//            if (requestAttributes == null){
//                throw new Exception("无法获取当前请求");
//            }
//            HttpServletRequest request = requestAttributes.getRequest();
//            if (request == null){
//                throw new Exception("无法获取当前请求");
//            }
//            User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
            // 调用成功后，次数 + 1
            UserInterfaceLog userInterfaceLog = new UserInterfaceLog();
            userInterfaceLog.setUserId(user.getId());
            userInterfaceLog.setInterfaceId(apiCount.interfaceId());
            userInterfaceLog.setOperationTime(new Date());
            userInterfaceLog.setInterfaceName(apiCount.interfaceName());
            userInterfaceLogService.save(userInterfaceLog);
            return result;
        } catch (Throwable throwable) {
            log.error("接口调用异常", throwable);
            throw throwable;
        }
    }

    /**
     * 获取当前请求
     */
    private HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }
}

